//连接数据库
var db = openDatabase('mydb', '1.0', 'WJN_DB', 2 * 1024 * 1024);
var msg;

//db.transaction(function(tx) {
//	//	tx.executeSql('DROP TABLE t_pc');
//	//tx.executeSql('DROP TABLE t_cart');
//	tx.executeSql('CREATE TABLE IF NOT EXISTS t_pc (id unique, name,title,branch,price,img)');
//	tx.executeSql('CREATE TABLE IF NOT EXISTS t_cart (id unique, u_id,pc_id,count,type)');
//	tx.executeSql('CREATE TABLE IF NOT EXISTS t_order (id unique, cart_id , time ,status)');
//	tx.executeSql('CREATE TABLE IF NOT EXISTS t_msg (id unique, img , title ,txt,pc_id)');
//	tx.executeSql('INSERT INTO t_pc (id, name,title,branch,price,img) VALUES (1, "联想330c","联想(Lenovo)330C15.6英寸英特尔八代酷睿商务影音笔记本电脑(i5-8250U 4G 1T+128G MX110 Office)黑","联想",9999.00,"img/lx_330c.jpg")');
//	tx.executeSql('INSERT INTO t_pc (id, name,title,branch,price,img) VALUES (2, "华硕FL8000UF","华硕顽石(ASUS) 五代FL8000UF 15.6英寸影音笔记本电脑(i7-8550U 8G 128GSSD+1T MX130 2G独显 FHD)星空灰","华硕",5199.00,"img/hs_01.jpg")');
//	tx.executeSql('INSERT INTO t_pc (id, name,title,branch,price,img) VALUES (3, "AppleMQD32CH/A","Apple MacBook Air 13.3英寸笔记本电脑 银色(2017款Core i5 处理器/8GB内存/128GB闪存 MQD32CH/A)","苹果",6099.00,"img/apple01.jpg")');
//	tx.executeSql('INSERT INTO t_pc (id, name,title,branch,price,img) VALUES (4, "惠普HP ZHAN 66 Pro G1","惠普（HP）战66 Pro G1 14英寸轻薄笔记本电脑（i5-8250U 8G 360G PCIe SSD 标压MX150 2G独显）银色","惠普",5299.00,"img/hp01.jpg")');
//	tx.executeSql('INSERT INTO t_cart (id, u_id,pc_id,count,type) VALUES (1,3,1,1,0)');
//	tx.executeSql('INSERT INTO t_cart (id, u_id,pc_id,count,type) VALUES (2,3,3,4,0)');
//	tx.executeSql('INSERT INTO t_order (id, cart_id,time,status) VALUES (1,1,"2019-10-1","未付款")');
//	tx.executeSql('INSERT INTO t_msg (id, img,title,txt,pc_id) VALUES (1,"img/msg1.jpg","华硕笔记本","华硕顽石独显轻薄本,下单立减400元",2)');
//	tx.executeSql('INSERT INTO t_msg (id, img,title,txt,pc_id) VALUES (2,"img/msg2.jpg","联想旗舰店","用券立减500 先抢先得 到手价7999",1)');
//	tx.executeSql('INSERT INTO t_msg (id, img,title,txt,pc_id) VALUES (3,"img/apple01.jpg","apple电脑","纤巧轻薄 超长续航 更多产品请点击",3)');
//	tx.executeSql('INSERT INTO t_msg (id, img,title,txt,pc_id) VALUES (4,"img/msg3.jpg","惠普笔记本","致静致凉，轻薄时尚！IPS全高清视野",4)');
//
//	getMainView("SELECT * FROM t_pc");
//	});

//加载首页
$(document).on("pageshow", "#pageOne", function() {
	getMainView("SELECT * FROM t_pc");
});
//根据sql语句加载页面
function getMainView(sql) {
	db.transaction(function(tx) {
		tx.executeSql(sql, [], function(tx, results) {
			var len = results.rows.length,
				i;
			for(i = 0; i < len; i++) {
				document.querySelector('#status').innerHTML += "<div class='ui-grid-a'><div class='ui-block-a'><img src='" +
					results.rows.item(i).img + "' width='90%' /></div><div class='ui-block-b'><p>" +
					results.rows.item(i).title + "</p><p>价格：" +
					results.rows.item(i).price + "</p><a target='_blank' href='details.html?id=" +
					results.rows.item(i).id + "' class='ui-btn'>详情</a></div></div>";
			}
		}, null);
	});
}

//购物车检查是否登录
$(document).on("pageshow", "#pageThree", function() {
	var i;
	var user = sessionStorage.getItem('user');
	if(user == null) {
		alert("请先登录！");
		window.location.href = "login.html";
	} else {
		var userJsonStr = sessionStorage.getItem('user');
		userEntity = JSON.parse(userJsonStr);
		var u_id = userEntity.id; //获取当前用户id
		//载入用户购物车
		getPcIdByUserId(u_id);
	}
});
//用户中心检查是否登录
$(document).on("pageshow", "#pageFour", function() {
	var user = sessionStorage.getItem('user');
	if(user == null) {
		alert("请先登录！");
		window.location.href = "login.html";
	} else {
		// 获取sessionStorage中的用户信息
		var userJsonStr = sessionStorage.getItem('user');
		userEntity = JSON.parse(userJsonStr);
		document.querySelector('#userManage').innerHTML = "<div class='ui-grid-a'><div class='ui-block-a'><img src='" + userEntity.img + "' style = 'border-radius: 50%;'" +
			"width = '90%'/></div><div class = 'ui-block-b' ><h1>" + userEntity.name + "</h1><p><button onclick='javascript:logout();' >注销</button></p></div></div>";
	}
});

//注销方法
function logout() {
	//清空sessionStorage
	sessionStorage.clear();
	window.location.href = 'index.html';
}

//根据用户id获得该用户购物车中所有的商品id
function getPcIdByUserId(userId) {
	var pc_id, count;
	db.transaction(function(tx) {
		tx.executeSql('SELECT * FROM t_cart where type = 0 and u_id =' + userId, [], function(tx, results) {
			var len = results.rows.length,
				i;
			document.querySelector("#cart_view").innerHTML = "";
			for(i = 0; i < len; i++) {
				pc_id = results.rows.item(i).pc_id;
				count = results.rows.item(i).count;
				getPcById(pc_id, count, results.rows.item(i).id);
			}
		}, null);

	});
}

//根据pcid获取pc信息 用于购物车显示
function getPcById(pc_id, count, cart_id) {
	db.transaction(function(tx) {
		tx.executeSql('SELECT * FROM t_pc where id =' + pc_id, [], function(tx, results) {
			if(results.rows.length > 0) {
				var pc = {
					id: results.rows.item(0).id,
					name: results.rows.item(0).name,
					title: results.rows.item(0).title,
					price: results.rows.item(0).price,
					img: results.rows.item(0).img,
					count: count
				}
				var pc_entity = JSON.stringify(pc);
				initCart(pc_entity, cart_id);
			} else {
				alert("发生错误");
			}
		}, null);

	});
}

//绘制购物车
function initCart(pc_entity, cart_id) {
	var pc = JSON.parse(pc_entity);
	document.querySelector("#cart_view").innerHTML += "<div class='ui-grid-a'><div class='ui-block-a'><img src='" + pc.img + "' width='90%' />" +
		"</div><div class='ui-block-b'><h3>" + pc.name + "</h3>" +
		"<p>单价：" + pc.price + "</p>数量：<div class='mui-numbox' data-numbox-step='1' data-numbox-min='1' data-numbox-max='100'>" +
		"<button  class='mui-btn mui-numbox-btn-minus' type='button'>-</button><input data-role='none' class='mui-numbox-input' type='number' id='countPage' value='" + pc.count + "'/>" +
		"<button  class='mui-btn mui-numbox-btn-plus' type='button'>+</button></div>" +
		"<button onclick='javascript:pay(" + cart_id + ")' style='margin-top: 10px;' type='button' class='mui-btn mui-btn-danger'>结算</button></div></div>";
	//是数字选择器生效
	mui('.mui-numbox').numbox();
	//将购物车存入sessionStorage
	//	if(sessionStorage.getItem('cart_list') == null) {
	//		var cart_list = [{
	//			id: cart_id,
	//			name: pc.name,
	//			price: pc.price,
	//			count: pc.count
	//		}];
	//		sessionStorage.setItem('cart_list', JSON.stringify(cart_list));
	//	} else {
	//		var cart_item = {
	//			id: cart_id,
	//			name: pc.name,
	//			price: pc.price,
	//			count: pc.count
	//		}
	//		alert(sessionStorage.getItem('cart_list'));
	//		var cart_list = JSON.parse(sessionStorage.getItem('cart_list'));
	//		
	//		//sessionStorage.setItem('cart_list', JSON.stringify(cart_list));
	//	}

}

//结算
function pay(cart_id) {
	//获取页面数字框数量
	var conutPage = $(countPage).val();
	db.transaction(function(tx) {
		//更新数量
		tx.executeSql('update t_cart set count = ' + conutPage + ' where id = ' + cart_id);
		//购物车信息导出到订单页面
		tx.executeSql('SELECT * FROM t_pc,t_cart where t_pc.id = t_cart.id and t_cart.id =' + cart_id, [], function(tx, results) {
			//获取用户信息
			var userJsonStr = sessionStorage.getItem('user');
			var totolPrice = results.rows.item(0).price * results.rows.item(0).count; //总价
			userEntity = JSON.parse(userJsonStr);
			document.querySelector('#orderdetails').innerHTML = "<img src='" + results.rows.item(0).img + "' width='80%' />" +
				"<p>商品名称：" + results.rows.item(0).name + "</p>" +
				"<p>商品单价：" + results.rows.item(0).price + "</p>" +
				"<p>购买数量：" + results.rows.item(0).count + "</p>" +
				"<p>收获地址：" + userEntity.addr + "</p>" +
				"<p>联系电话：" + userEntity.phone + "</p>" +
				"<p>联系人：" + userEntity.realname + "</p>";
			document.querySelector('#jiesuan').innerHTML = "<div class='ui-block-a'><h3 id='total' style='text-align: center;'>合计：" + totolPrice + "</h3></div>" +
				"<div class='ui-block-b'><button onclick='javascript:confirmOrder(" + cart_id + ")' data-role = 'none' style='width: 100%;height: 50px;' type='button' class='mui-btn mui-btn-danger'>确认订单</button></div>";
		}, null);
	});
	window.location.href = '#pageOrder';

}
//确认订单
function confirmOrder(cart_id) {
	var myDate = new Date();
	var year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
	var month = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
	var days = myDate.getDate(); //获取当前日(1-31)
	var time = year + "-" + month + "-" + days;

	db.transaction(function(tx) {
		var id;
		tx.executeSql('SELECT * FROM t_order', [], function(tx, results) {
			id = results.rows.length + 1;
			tx.executeSql("INSERT INTO t_order (id, cart_id,time,status) VALUES (" + id + "," + cart_id + ",'" + time + "','未付款')");
			//将购物车修改为不可见
			tx.executeSql("update t_cart set type = 1 where id = " + cart_id);
		}, null);

	});
	window.location.href = '#order';
}
//载入订单
$(document).on("pageshow", "#order", function() {
	getOrderList();
});

//获取订单列表
function getOrderList() {
	db.transaction(function(tx) {
		var userJsonStr = sessionStorage.getItem('user');
		userEntity = JSON.parse(userJsonStr);
		var u_id = userEntity.id; //获取当前用户id
		tx.executeSql('SELECT * FROM t_pc,t_order,t_cart where t_order.cart_id = t_cart.id and t_cart.pc_id = t_pc.id and t_cart.u_id = ' + u_id, [], function(tx, results) {
			var len = results.rows.length,
				i;
			//			document.querySelector('#orderlist').innerHTML += "<ul  data-role='mui-table-view'>";
			document.querySelector('#orderlist').innerHTML = "";
			for(i = len - 1; i >= 0; i--) {
				var total = results.rows.item(i).price * results.rows.item(i).count;
				document.querySelector('#orderlist').innerHTML += "<div class='ui-grid-a'><div class='ui-block-a'><img src='" + results.rows.item(i).img + "' width='80%'/></div>" +
					"<div class='ui-block-b'><h3>" + results.rows.item(i).name + "</h3><p>单价：" + results.rows.item(i).price + "</p><p>数量：" + results.rows.item(i).count + "</p>" +
					"<p>金额：" + total + "</p><p>下单时间：" + results.rows.item(i).time + "</p><p>订单状态：" + results.rows.item(i).status + "</p></div></div><hr>";

			}
			//			document.querySelector('#orderlist').innerHTML += "</ul>";

			//document.querySelector('#orderlistview').innerHTML = "<li><a><img src='img/apple01.jpg' /><h3>联想330c</h3><p>单价：9999</p><p>数量：9</p><p>金额：11111</p><p>下单时间：2019-10-1</p><p>订单状态：待支付</p></a></li>";
			//	$('#orderlistview').listview('refresh');
		}, null);

	});
}

//消息界面
$(document).on("pageshow", "#pageTwo", function() {
	db.transaction(function(tx) {
		tx.executeSql('SELECT * FROM t_msg ', [], function(tx, results) {
			alert('msg');
			var len = results.rows.length,
				i;
			var htmltxt = '';
			for(i = 0; i < len; i++) {
				htmltxt += "<li class='mui-table-view-cell mui-media'><a href='details.html?id="+results.rows.item(i).pc_id+"' target='_blank' class='mui-navigate-right'><img class='mui-media-object mui-pull-left' src='"
				+results.rows.item(i).img+
				"'><div class='mui-media-body'>"+results.rows.item(i).title+"<p class='mui-ellipsis'>"+results.rows.item(i).txt+"</p></div></a></li>";
			}
			$('#msg_list').html(htmltxt);
		}, null);

	});

});